export function sortParams(obj: object): string {
  function sortKeys(obj: any): any {
    if (Array.isArray(obj)) {
      return obj.map(item => sortKeys(item)).sort();
    } else if (typeof obj === 'object' && obj !== null) {
      const sortedObj: Record<string, any> = {};
      Object.keys(obj).sort().forEach(key => {
        if (typeof obj[key] !== 'undefined') {
          sortedObj[key] = sortKeys(obj[key]);
        }
      });
      return sortedObj;
    }
    return obj;
  }


  const sortedObj = sortKeys(obj);
  return Object.keys(sortedObj).map(key => {
    if (['[object Object]', '[object Array]'].includes(Object.prototype.toString.call(sortedObj[key]))) {
      return `${key}=${JSON.stringify(sortedObj[key])}`
    } else {
      return `${key}=${sortedObj[key]}`
    }
  }).join('&');
}

// 是否文件
export function isFileOrBlob(value: any): boolean {
  return value instanceof File || value instanceof Blob;
}

// 获取地址栏参数
export function getQueryParam(paramName: string) {
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  return urlParams.get(paramName);
}

// 往url拼接参数
export function appendParamsToUrl(url: string, params: Record<string, string | undefined | null>): string {
  const filteredParams: Record<string, string> = Object.fromEntries(
    Object.entries(params).filter(([_, value]) => value != null) as [string, string][]
  );
  const queryString = new URLSearchParams(filteredParams).toString();
  const separator = url.includes("?") ? "&" : "?";
  return `${url}${separator}${queryString}`;
}

// app通讯
type Msg = {
  type: string,
  payload: Record<string, any>
}
export function postMsg(msg: Msg):void{
  try{
    // @ts-ignore
    window.ReactNativeWebView.postMessage(JSON.stringify(msg))
  }catch(err){
    // console.error(err)
  }
}